import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { encryptData, decryptData } from "@/utils/crypto";

export interface AuthUser {
  userId: string;
  email: string;
}

export const useAuthhook = () => {
  const [ituser, setItuser] = useState<AuthUser | null>(null);
  const router = useRouter();

  // 初始化时从 sessionStorage 获取并解密用户信息
  useEffect(() => {
    const encryptedUserData = sessionStorage.getItem("user");
    if (encryptedUserData) {
      const userData = decryptData(encryptedUserData);
      if (userData) {
        setItuser(userData);
      }
    }
  }, []);

  // 登录时加密用户信息再存储
  const login = (userData: AuthUser) => {
    const encrypted = encryptData(userData);
    if (!encrypted) {
      // 可选：处理加密失败逻辑，如提示错误或使用默认值
      console.error("加密失败");
      return;
    }
    sessionStorage.setItem("user", encrypted);
    setItuser(userData);
  };

  // 登出时清除
  const logout = () => {
    sessionStorage.removeItem("user");
    setItuser(null);
  };

  return {
    ituser,
    login,
    logout,
    isAuthenticated: !!ituser,
  };
};
